"""
    请求地址：https://news.ifeng.com/c/special/7tPlDSzDgVk?needpage=1&webkit=1
"""
import re
import csv
import json
import requests

def get_json(url):
    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
    }
    try:
        response = requests.get(url=url, headers=header)
        response.raise_for_status()
        response.encoding = response.apparent_encoding
        return response.text
    except Exception as e:
        print(e)

def get_parse():
    response = get_json(url='https://news.ifeng.com/c/special/7tPlDSzDgVk?needpage=1&webkit=1')
    if response:
        name = '中国'
        data = json.loads(re.findall('var allData = (.*?);', response)[0])['leiji']['dataList'][0]
        quezhen = data['quezhen']
        siwang = data['siwang']
        save_csv([name,quezhen,siwang])
    else:
        print('数据解析失败')

def save_csv(data):
    writer.writerow(data)


if __name__ == '__main__':
    fp = open('world.csv', 'a', encoding='utf-8', newline='')
    writer = csv.writer(fp)
    writer.writerow(['国家','累计确诊','死亡人数'])
    get_parse()
    fp.close()
